<template>
  <div>
    <el-form :model="condition" size="small" :inline="true">
      <el-form-item label="杆塔编号">
        <el-input v-model="condition.id" placeholder="请输入杆塔编号" clearable />
      </el-form-item>
      <el-form-item label="杆塔序号">
        <el-input v-model="condition.orders" placeholder="请输入杆塔序号" clearable />
      </el-form-item>
      <el-form-item label="杆塔位置">
        <el-input v-model="condition.position" placeholder="请输入杆塔位置" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
        <el-button icon="el-icon-refresh-left" @click="reset()">重置</el-button>
        <el-button icon="el-icon-circle-plus-outline" @click="showtowerDialog()">新增</el-button>
      </el-form-item>
    </el-form>
    <div style="height: 34px">
      <el-pagination background align="right" v-show="total > 0"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="currentPage"
                     :page-sizes="pageSizes"
                     :page-size="pageSize"
                     layout="total, sizes, prev, pager, next"
                     :total="total">
      </el-pagination>
    </div>
    <!-- el-table的data属性就是用来绑定这个表格显示的数据 -->
    <el-table :data="towers" height="250" style="width: 100%">
      <!-- el-table-column表示表格的每一列信息 label属性表示表头的名称
         prop表示绑定的字段名 width属性表示这一列显示的宽度-->
      <el-table-column prop="id" label="杆塔编号"/>
      <el-table-column prop="orders" label="杆塔序号"/>
      <el-table-column prop="position" label="杆塔位置"/>
      <el-table-column prop="state" label="杆塔状态">
        <template slot-scope="scope">
          <span v-if="scope.row.state === 0">未启用</span>
          <span v-else>已启用</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="showtowerDialog(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.state === 1" type="text" @click="changeUseState(scope.row.id, 1, 0)">停用</el-button>
          <el-button v-else type="text" @click="changeUseState(scope.row.id,0, 1)">启用</el-button>
          <el-button type="text" @click="deleteTower(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="`${towerDialog.isUpdate ? '编辑杆塔' : '新增杆塔'}`" :visible.sync="towerDialog.visible" width="50%">
      <el-form :model="towerDialog.editTower" :rules="towerDialog.towerRules" ref="towerRules" :inline="true">
        <el-form-item label="杆塔编号">
          <el-input v-model="towerDialog.editTower.id" :readonly="towerDialog.isUpdate"/>
        </el-form-item>
        <el-form-item label="杆塔序号">
          <el-input v-model="towerDialog.editTower.orders" :readonly="towerDialog.isUpdate"/>
        </el-form-item>
        <el-form-item label="杆塔位置" >
          <el-input v-model="towerDialog.editTower.position"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="save">保 存</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
import isNumber from "vue-router";

export default {
  name: "Tower",
  data(){
    return {
      condition: {
        id: '',
        orders: '',
        position: ''
      },
      auditStates: ['待分配', '已分配', '执行中', '已完成'],
      towers: [],
      currentPage: 1, //分页的默认页码应该是第一页
      pageSizes: [50, 100, 150, 200, 400], //可选的每页显示条数
      pageSize: 50, //每页显示条数
      total: 0, //查询的总条数，默认值为0，查询之后才会赋值
      towerDialog: {
        visible: false,
        isUpdate: false,
        editTower: {
          id: '',
          orders: '',
          position: '',
        },
        towerRules: {
          id: [
            {required: true, message: '杆塔编号不能为空(ETxxx)', trigger: ['blur', 'change']}
          ],
          orders: [
            {required: true, message: ' 杆塔序号不能为空(CNxxxx)', trigger: ['blur', 'change']}
          ],
          position: [
            {required: true, message: '杆塔位置不能为空', trigger: ['blur', 'change']}
          ]
        }
      }
    }
  },
  methods: {
    handleSizeChange(val){//这个函数是用来监听每页显示条数的变更
      this.currentPage = 1
      this.pageSize = val
      this.search()
    },
    handleCurrentChange(val){//这个函数是用来监听当前页码变化
      this.currentPage = val
      this.search()
    },
    search(){
      this.doGet('/tower', {
        id: this.condition.id,
        orders: this.condition.orders,
        position: this.condition.position,
        currentPage: this.currentPage,
        pageSize: this.pageSize
      }, resp => {
        this.towers = resp.records
        this.total = resp.total
      })
    },
    changeUseState(id, oldState, newState){
      this.doPut('/tower/state', {
        id: id,
        state: newState
      }, resp => {
        if(resp){
          this.$message.success(`${newState === 0 ? '停用': '启用'}成功`)
          this.search()
        } else {
          this.$message.error(`${newState === 0 ? '停用': '启用'}失败`)
        }
      })
    },
    showtowerDialog(defectTask){
      if(defectTask){
        this.towerDialog.isUpdate = true
        //首先获取user对象的属性集合，然后遍历这个集合，将每一个属性值拷贝到editTower对象中
        Object.keys(defectTask).forEach(key => this.towerDialog.editTower[key] = defectTask[key])
      } else {
        this.towerDialog.isUpdate = false
      }
      this.towerDialog.visible = true
    },
    closeDialog(){
      this.towerDialog.visible = false
      this.towerDialog.editTower = {
        id: '',
        orders: '',
        position: '',
        state: '',
      }
      //重置所有的表单验证，这样可以清除提示信息
      this.$refs['towerRules'].resetFields();
    },
    save(){
      this.$refs['towerRules'].validate(valid => {
        if(valid){

          var id = this.towerDialog.editTower.id
          var orders = this.towerDialog.editTower.orders

          if(!id.startsWith("ET")||!orders.startsWith("CN")){
            return false;
          }


          if(this.towerDialog.isUpdate){
            //这里就可以提交信息去后台服务器保存数据
            this.doPut('/tower', this.towerDialog.editTower, resp => {
              if(resp.code==='200'){
                this.$message.success("保存成功")
                this.closeDialog()
                this.search()
              } else {
                this.$message.error("杆塔编号或序号已存在")
              }
            })
          } else {
            this.doPost('/tower', this.towerDialog.editTower, resp => {
              if(resp){
                this.$message.success("保存成功")
                this.closeDialog()
                this.search()
              } else {
                this.$message.error("杆塔编号或序号已存在")
              }
            })
          }
        } else {
          return false
        }
      })
    },
    deleteTower(tower){
      this.showConfirm(`确定要删除杆塔${tower.id}吗?`, () => {
        //点击确定按钮后才会执行删除动作
        this.doDelete(`/tower/${tower.id}`, {}, resp  => {
          if(resp){
            this.$message.success("删除成功")
            this.search()
          } else {
            this.$message.error("删除失败")
          }
        })
      })
    },
    reset(){
      this. condition = {
        name: '',
        state: '',
        defectUser: ''
      }
      this.search()
    }
  },
  mounted() { //这个函数是一个钩子函数，有vue自动调用，在页面完成挂载之后就会调用这个函数
    this.search()
  }
}
</script>

<style scoped>

</style>
